//
//  ViewController.swift
//  BWToolKit
//
//  Created by 1906457616@qq.com on 01/28/2022.
//  Copyright (c) 2022 1906457616@qq.com. All rights reserved.
//

import UIKit
import BWToolKit


enum DemoOSS {
    static let app1 = OSS(idKey: "", secretKey: "", bucketName: "", endpointUrl: "")
    static let app2 = OSS(idKey: "", secretKey: "", bucketName: "", endpointUrl: "")
}

extension String {
    static func makeOssObjectKey(with filetype: OSS.FileType) -> String {
        let df = DateFormatter()
        df.dateFormat = "yyyy/MM/dd"
        let key = "ios/" + df.string(from: .init()) + "/\(UUID().uuidString).\(filetype.rawValue)"
        return key
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        Notifier.observe([NSNotification.Name.UIApplicationDidEnterBackground], on: self) { n in
            print(n.name)
        }
        
        Keyboarder.observe(on: self) { k in
            print(k)
        }
        
        print(Lets.appRootVC)
        print(Lets.safeAreaInsets)
    }
    
    /*
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        
        view.subviews.first{ $0.tag == 999 }?.removeFromSuperview()
        
        let v = UIView(frame: layoutSafeArea)
        v.tag = 999
        view.addSubview(v)
        v.backgroundColor = .orange
        
        print(layoutSafeArea)
    }*/
    
    @IBAction func testOSSFileUpload(_ sender: UIButton) {
        return
        guard
            let aURL = Bundle.main.url(forResource: "test.zip", withExtension: nil),
            let data = try? Data(contentsOf: aURL) else {
            return
        }
        sender.isEnabled = false
        DemoOSS.app1.uploadFile(data, objectKey: .makeOssObjectKey(with: .zip)) { p in
            sender.setTitle("\(p * 100)%%", for: .normal)
        } success: { url in
            print(url)
        } failure: { err in
            print(err.localizedDescription)
        }
    }
    
    @IBAction func presentNewPage(){
        Jumper.jump(.present(.init(), style: .formSheet))
    }
    @IBAction func pushNewPage(){
        Jumper.jump(.push(.init()))
    }

    deinit {
        Notifier.removeAll(for: self)
        Keyboarder.remove(for: self)
        timer?.cancel()
    }
    
    var counts = 0
    var timer: DispatchSourceTimer?
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.window?.endEditing(true)
        
//        timer = GCD.dispatchTimer(interval: 1) { [weak self] in
//            guard let self = self else { return }
//            self.counts += 1
//            print(self.counts)
//        }
        
//        GCD.asyncAfter(seconds: 5, in: .main) {
//            print("After 5s executed!")
//            self.view.backgroundColor = .green
//        }
        
//        GCD.Group.async(items: [
//            downloadItem(0),
//            downloadItem(1),
//            downloadItem(2),
//        ], notify: .main, completion: { errs in
//            if !errs.isEmpty {
//                print("Some tasks were failed: \(errs)")
//                self.view.backgroundColor = .systemRed
//            }
//            else {
//                print("All success!")
//                self.view.backgroundColor = .systemGreen
//            }
//        })
        
        
        
    }
    
    func request(task: Int, time: TimeInterval, completion: (()->Void)?) {
        DispatchQueue.global().async {
            print("Started: \(task) ... ➡️➡️➡️➡️➡️➡️")
            Thread.sleep(forTimeInterval: time)
            print("Finished: \(task) ... ✅✅✅✅✅✅✅✅✅✅✅")
            GCD.asyncInMainQueue(completion ?? {})
        }
    }
    
    func downloadItem(_ index: Int) -> GCD.Group.Item {
        let item = GCD.Group.Item(taskId: .init(index))
        item.handler = {
            GCD.Queue.global().queue.async{ [weak item] in
                print("[\(index)] Started")
                Thread.sleep(forTimeInterval: Double(3-index))
                print("[\(index)] Finished")
                
                if index == 2 {
                    let err = NSError(domain: "Wrong", code: index, userInfo: nil)
                    item?.completion?(.init(taskId: .init(index), error: err))
                }
                else {
                    item?.completion?(nil)
                }
            }
        }
        return item
    }

}

